﻿@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container-fluid">
    <el-card shadow="hover">
        <template #header>
            <div style="font-size: 18px; font-weight: bold;">体重数据概览</div>
        </template>

        <el-row :gutter="20" style="margin-bottom: 20px;">
            <!-- 当前体重 -->
            <el-col :lg="6" :md="6" :sm="12">
                <el-card shadow="hover" class="stat-card" :body-style="{padding: '15px'}">
                    <div style="color: #409EFF; margin-bottom: 5px;">当前体重</div>
                    <div style="font-size: 24px; font-weight: bold; margin-bottom: 10px;">
                        {{ stats.currentWeight ? stats.currentWeight + ' kg' : '--' }}
                    </div>
                    <el-progress :percentage="70" :show-text="false" height="6"></el-progress>
                    <div style="margin-top: 5px; font-size: 12px; color: #909399;">
                        {{ stats.currentWeightTime ? formatDate(stats.currentWeightTime) : '--' }}
                    </div>
                </el-card>
            </el-col>
            <!-- 最高体重 -->
            <el-col :lg="6" :md="6" :sm="12">
                <el-card shadow="hover" class="stat-card" :body-style="{padding: '15px'}">
                    <div style="color: #F56C6C; margin-bottom: 5px;">历史最高</div>
                    <div style="font-size: 24px; font-weight: bold; margin-bottom: 10px;">
                        {{ stats.maxWeight ? stats.maxWeight + ' kg' : '--' }}
                    </div>
                    <el-progress :percentage="100" :show-text="false" height="6"></el-progress>
                    <div style="margin-top: 5px; font-size: 12px; color: #909399;">
                        {{ stats.maxWeightTime ? formatDate(stats.maxWeightTime) : '--' }}
                    </div>
                </el-card>
            </el-col>
            <!-- 最低体重 -->
            <el-col :lg="6" :md="6" :sm="12">
                <el-card shadow="hover" class="stat-card" :body-style="{padding: '15px'}">
                    <div style="color: #67C23A; margin-bottom: 5px;">历史最低</div>
                    <div style="font-size: 24px; font-weight: bold; margin-bottom: 10px;">
                        {{ stats.minWeight ? stats.minWeight + ' kg' : '--' }}
                    </div>
                    <el-progress :percentage="50" :show-text="false" height="6"></el-progress>
                    <div style="margin-top: 5px; font-size: 12px; color: #909399;">
                        {{ stats.minWeightTime ? formatDate(stats.minWeightTime) : '--' }}
                    </div>
                </el-card>
            </el-col>
            <!-- 累计变化 -->
            <el-col :lg="6" :md="6" :sm="12">
                <el-card shadow="hover" class="stat-card" :body-style="{padding: '15px'}">
                    <div style="color: #E6A23C; margin-bottom: 5px;">累计变化</div>
                    <div style="font-size: 24px; font-weight: bold; margin-bottom: 10px;" :style="{color: stats.totalChange > 0 ? '#F56C6C' : stats.totalChange < 0 ? '#67C23A' : '#606266'}">
                        {{ stats.totalChange !== undefined ? (stats.totalChange >= 0 ? '+' + stats.totalChange.toFixed(2) : stats.totalChange.toFixed(2)) + ' kg' : '--' }}
                    </div>
                    <el-progress :percentage="60" :show-text="false" height="6"></el-progress>
                    <div style="margin-top: 5px; font-size: 12px; color: #909399;">相比初始记录</div>
                </el-card>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <!-- 体重趋势图表 -->
            <el-col :lg="16">
                <el-card shadow="hover">
                    <template #header>
                        <div class="clearfix">
                            <span style="font-weight: bold;">体重趋势图</span>
                            <el-button-group style="float: right;">
                                <el-button v-for="day in trendDays"
                                           :key="day.value"
                                           size="small"
                                           :type="selectedDays === day.value ? 'primary' : 'default'"
                                           plain
                                           @@click="selectDays(day.value)">
                                    {{ day.label }}
                                </el-button>
                            </el-button-group>
                        </div>
                    </template>
                    <div class="chart-container">
                        <div id="weightTrendChart" style="height: 300px;"></div>
                    </div>
                </el-card>
            </el-col>

            <!-- 统计信息 -->
            <el-col :lg="8">
                <el-card shadow="hover">
                    <template #header>
                        <div style="font-weight: bold;">统计信息</div>
                    </template>
                    <el-list class="stat-list">
                        <el-list-item>
                            <div slot="main">
                                <span style="font-weight: bold;">相比上周</span>
                                <span style="float: right;">{{ formatWeightChange(stats.changeFromLastWeek) }}</span>
                            </div>
                        </el-list-item>
                        <el-list-item>
                            <div slot="main">
                                <span style="font-weight: bold;">相比上月</span>
                                <span style="float: right;">{{ formatWeightChange(stats.changeFromLastMonth) }}</span>
                            </div>
                        </el-list-item>
                        <el-list-item>
                            <div slot="main">
                                <span style="font-weight: bold;">平均每周变化</span>
                                <span style="float: right;">{{ formatWeightChange(stats.avgWeeklyChange, ' kg/周') }}</span>
                            </div>
                        </el-list-item>
                        <el-list-item>
                            <div slot="main">
                                <span style="font-weight: bold;">平均每月变化</span>
                                <span style="float: right;">{{ formatWeightChange(stats.avgMonthlyChange, ' kg/月') }}</span>
                            </div>
                        </el-list-item>
                        <el-list-item>
                            <div slot="main">
                                <span style="font-weight: bold;">记录总数</span>
                                <span style="float: right;">{{ stats.totalRecords || '--' }}</span>
                            </div>
                        </el-list-item>
                        <el-list-item>
                            <div slot="main">
                                <span style="font-weight: bold;">记录天数</span>
                                <span style="float: right;">{{ stats.recordDays || '--' }}</span>
                            </div>
                        </el-list-item>
                    </el-list>
                    <div style="margin-top: 20px;">
                        <el-button type="primary" @@click="goToTrendAnalysis" icon="el-icon-data-line" style="width: 100%; margin-bottom: 10px;">
                            详细趋势分析
                        </el-button>
                        <el-button type="success" @@click="goToQuickRecord" icon="el-icon-plus" style="width: 100%;">
                            快速记录体重
                        </el-button>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </el-card>
</div>

@section Scripts {
    <script src="~/js/echarts.min.js"></script>
    <script>
        var dashboardApp = new Vue({
            el: '#app',
            mixins: [curdMixin],
            data: {
                stats: {},
                weightChart: null,
                selectedDays: 30,
                trendDays: [
                    { label: '7天', value: 7 },
                    { label: '30天', value: 30 },
                    { label: '90天', value: 90 },
                    { label: '180天', value: 180 },
                    { label: '1年', value: 365 }
                ]
            },
            mounted: function() {
                this.initChart();
                this.loadStats();
                this.loadTrendData(this.selectedDays);
            },
            methods: {
                initChart: function() {
                    this.weightChart = echarts.init(document.getElementById('weightTrendChart'));
                    this.updateChartOptions([], []);
                },
                updateChartOptions: function(groupedData, allDates) {
                    console.log('更新图表选项，数据组数：', Object.keys(groupedData).length, '，日期数量：', allDates.length);
                    // 获取所有唯一的时段
                    const periods = [...new Set(Object.values(groupedData).flatMap(dayData => 
                        dayData.map(item => item.PeriodName || '未知时段')
                    ))];
                    
                    // 为每个时段准备数据
                    const series = periods.map((period, index) => {
                        // 预定义颜色数组
                        const colors = ['#4B9DFF', '#67C23A', '#F56C6C', '#E6A23C', '#909399', '#C0C4CC'];
                        const color = colors[index % colors.length];
                        
                        // 为每个日期准备数据点
                        const data = allDates.map(date => {
                            const dayData = groupedData[date];
                            if (!dayData) return null;
                            const item = dayData.find(d => d.PeriodName === period);
                            return item ? item.Weight : null;
                        });
                        
                        return {
                            name: period,
                            type: 'line',
                            data: data,
                            smooth: true,
                            connectNulls: true,
                            lineStyle: {
                                color: color,
                                width: 2
                            },
                            itemStyle: {
                                color: color
                            },
                            showSymbol: true,
                            symbol: 'circle',
                            symbolSize: 4
                        };
                    });
                    
                    // 计算所有数据中的最小值
                    let minValue = Infinity;
                    series.forEach(s => {
                        s.data.forEach(val => {
                            if (val !== null && val < minValue) {
                                minValue = val;
                            }
                        });
                    });
                    
                    // 设置y轴最小值为最小值减10，如果没有有效数据则默认为40
                    const yAxisMin = minValue === Infinity ? 40 : minValue - 1;
                    
                    this.weightChart.setOption({
                        tooltip: {
                            trigger: 'axis',
                            formatter: function(params) {
                                let result = params[0].name + '<br/>';
                                params.forEach(param => {
                                    if (param.value !== null) {
                                        result += param.marker + param.seriesName + ': ' + param.value + ' kg<br/>';
                                    }
                                });
                                return result;
                            }
                        },
                        legend: {
                            data: periods,
                            top: 0
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            boundaryGap: false,
                            data: allDates
                        },
                        yAxis: {
                            type: 'value',
                            min: yAxisMin,
                            axisLabel: {
                                formatter: '{value} kg'
                            }
                        },
                        series: series
                    });
                },
                selectDays: function(days) {
                    console.log('选择天数：', days);
                    this.loadTrendData(days);
                    this.selectedDays = days;
                    console.log('更新selectedDays后的值：', this.selectedDays);
                },
                loadStats: function() {
                    this.$http.get('/WeighInfo/stat')
                        .then(data => {
                            this.stats = data;
                        })
                        .catch(error => {
                            console.error('加载统计数据失败:', error);
                            this.$message.error('加载统计数据失败，请稍后重试');
                        });
                },
                loadTrendData: function(days) {
                    this.$http.get('/WeighInfo/trend/' + days)
                        .then(data => {
                            console.log('获取到的数据：', data);
                            // 按日期分组数据
                            const groupedData = {};
                            const allDates = new Set();
                            
                            data.forEach(item => {
                                const dateStr = this.formatDate(item.date, 'MM-dd');
                                allDates.add(dateStr);
                                
                                if (!groupedData[dateStr]) {
                                    groupedData[dateStr] = [];
                                }
                                
                                groupedData[dateStr].push({
                                    Weight: item.weight,
                                    PeriodName: item.periodName || '未知时段',
                                    Date: item.date
                                });
                            });
                            
                            // 转换日期集合为数组并排序
                            const sortedDates = Array.from(allDates).sort((a, b) => {
                                // 比较实际日期值而不仅仅是字符串
                                const getDateValue = (dateStr) => {
                                    const [month, day] = dateStr.split('-').map(Number);
                                    const now = new Date();
                                    let year = now.getFullYear();
                                    // 处理跨年度的情况
                                    if (month > now.getMonth() + 1) {
                                        year--;
                                    }
                                    return new Date(year, month - 1, day).getTime();
                                };
                                return getDateValue(a) - getDateValue(b);
                            });
                            
                            console.log('排序后的日期：', sortedDates);
                            console.log('分组数据：', groupedData);
                            
                            // 强制重新设置图表选项
                            if (this.weightChart) {
                                this.weightChart.dispose();
                                this.weightChart = echarts.init(document.getElementById('weightTrendChart'));
                            }
                            
                            this.updateChartOptions(groupedData, sortedDates);
                        })
                        .catch(error => {
                            console.error('加载趋势数据失败:', error);
                            this.$message.error('加载趋势数据失败，请稍后重试');
                        });
                },
                formatDate: function(date, format = 'yyyy-MM-dd HH:mm') {
                    if (!date) return '--';
                    let d = new Date(date);
                    return d.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: format.includes('MM') ? '2-digit' : 'numeric',
                        day: format.includes('dd') ? '2-digit' : 'numeric',
                        hour: format.includes('HH') ? '2-digit' : undefined,
                        minute: format.includes('mm') ? '2-digit' : undefined
                    }).replace(/\//g, '-');
                },
                formatWeightChange: function(value, unit = ' kg') {
                    if (value === undefined || value === null) return '--';
                    return (value >= 0 ? '+' + value.toFixed(2) : value.toFixed(2)) + unit;
                },
                navigateTo: function(url) {
                    window.location.href = url;
                },
                goToTrendAnalysis: function() {
                    this.navigateTo('/WeighInfo/TrendAnalysis');
                },
                goToQuickRecord: function() {
                    this.navigateTo('/WeighInfo');
                }
            }
        });
    </script>
}
